//shopcart仓库
import { reqGetShopCart, deleteShopCart, reqUpdateCart } from '@/api'
const state = {
    cartList: []
}
const actions = {
    async getShopCart({ commit }) {
        let result = await reqGetShopCart()
        // console.log(result);
        if (result.code == 200) {
            commit('GETSHOPCART', result.data)
        }
    },
    async delShopCart({ commit }, skuId) {
        let result = await deleteShopCart(skuId)
        console.log(result);
        if (result.code == 200) {
            return 'ok'
        } else {
            return Promise.reject(new Error('faile'))
        }
    },
    async updateCart({ commit }, { skuId, isChecked }) {
        let result = await reqUpdateCart(skuId, isChecked) //这里注意，传多个参数不要加{}
        console.log(result);
        if (result.code == 200) {
            return 'ok'
        } else {
            return Promise.reject(new Error('faile'))
        }
    },
    // 删除全部选中
    deleteAllChecked(context) {
        let PromiseAll = []
        context.getters.cartList.cartInfoList.forEach(item => {
            let promise = item.isChecked == 1 ? context.dispatch('delShopCart', item.skuId) : ''
            PromiseAll.push(promise)
        });
        return Promise.all(PromiseAll)
    },
    updateAllChecked({ dispatch, state }, isChecked) {
        let PromiseAll = []
        console.log(getters.cartList.cartInfoList);
        state.cartList[0].cartInfoList.forEach(item => {
            let promise = dispatch('updateCart', { skuId: item.skuId, isChecked })
            PromiseAll.push(promise)
            // console.log(promise);
        })
        // console.log(PromiseAll);
        return Promise.all(PromiseAll)
    }

}
const mutations = {
    GETSHOPCART(state, shopcart) {
        state.cartList = shopcart
    }
}
const getters = {
    cartList(state) {
        return state.cartList[0] || {}
    }
}
export default {
    state,
    actions,
    mutations,
    getters
}